﻿namespace Vibstudio.NetConfigurator.Engine.Configuration
{
    #region Namespaces

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;

    using Vibstudio.NetConfigurator.Common;
    using Vibstudio.NetConfigurator.Model;

    #endregion

    /// <summary>
    /// Configurator of appSettings sections
    /// </summary>
    [Obfuscation(Exclude = true, ApplyToMembers = false)]
    internal class AppConfigurator : IConfiguration
    {
        #region Public Methods and Operators

        public bool Configure(string filePath, List<ConfigurationSetting> settings)
        {
            XDocument document = XDocument.Load(filePath);

            bool configured = ConfigureApp(document, settings);
            if (configured)
            {
                document.Save(filePath);
            }

            return configured;
        }

        public void Reset()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Methods

        private bool ConfigureApp(XDocument document, IEnumerable<ConfigurationSetting> settings)
        {
            bool appChanged = true;

            try
            {
                IEnumerable<XElement> elements =
                    from e in document.Descendants("appSettings").Elements("add")
                    select e;

                foreach (ConfigurationSetting setting in settings)
                {
                    XElement element =
                        (from e in elements
                         where e.Attribute("key").Value == setting.Key
                         select e).FirstOrDefault();

                    if (element != null)
                    {
                        element.Attribute("value").SetValue(setting.Value);
                    }
                }
            }
            catch
            {
                appChanged = false;
            }

            return appChanged;
        }

        #endregion
    }
}